﻿using AdminSystem.Application;
using AdminSystem.Domain;
using AdminSystem.Repositories;
using AdminSystem.WebApi.DTOs;
using AdminSystem.WebApi.MedialRs.Commands.UserLogin;
using MediatR;

namespace AdminSystem.WebApi.MedialRs.CommandHandlers.UserLogin
{
    public class UserLoginCommandHandler : IRequestHandler<UserLoginCommand, ApiResult<List<UserDto>>>
    {
        private readonly IRepository<UserInfo> userInfo;
        private readonly IRepository<Role> repository;

        public UserLoginCommandHandler(IRepository<UserInfo> UserInfo,IRepository<Role> repository)
        {
            userInfo = UserInfo;
            this.repository = repository;
        }
        public async Task<ApiResult<List<UserDto>>> Handle(UserLoginCommand request, CancellationToken cancellationToken)
        {
            try
            {
                ApiResult<List<UserDto>> result = new ApiResult<List<UserDto>>();
                result.statusCode = StatusCode.FaieId;
                result.Message = "登录成功";
                var users = await userInfo.GetAll();
                var roles = await repository.GetAll();
                var user=from a in users
                         join b in roles on a.RoleId equals b.RoleId
                         where a.UserName == request.UserName
                         select new UserDto
                         {
                             UserId = a.UserId,
                             UserName = a.UserName,
                             UserPass = a.UserPass,
                             UserNickname = a.UserNickname,
                             RoleId = a.RoleId,
                             RoleName = b.RoleName
                         };
                var entity = user.FirstOrDefault();
                //var user = await userInfo.QueryFirstAsync(x => x.UserName == request.UserName);
                if (entity == null)
                {
                    result.statusCode = StatusCode.FaieId;
                    result.Message = "用户不存在";
                    return result;
                }
                if (entity.UserPass != request.Password)
                {
                    result.statusCode = StatusCode.FaieId;
                    result.Message = "密码错误";
                    return result;
                }
                // Assuming you want to return user details in the result
                result.statusCode = StatusCode.Success;
                result.Data = new List<UserDto> { new UserDto { UserId = entity.UserId, UserName = entity.UserName, UserPass = entity.UserPass, UserNickname = entity.UserNickname, RoleId = entity.RoleId,RoleName=entity.RoleName } };
                return result;
            }
            catch (Exception ex)
            {
                throw new Exception("An error occurred while processing the login request.", ex);
            }
        }
    }
}
